/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.util.Date;
import java.nio.ByteBuffer;
import java.util.*;
import java.lang.*;
import java.io.*;

/**
 *
 * @author pol
 */
public class Message {


    public Message(String text, String d, int msgID){        
        textDataOfMessage = text;
        dateOfMessageTransmisson = d;
        nextIdOfMessage = msgID;
    }
    
    public Message(String text, String d){        
        textDataOfMessage = text;
        dateOfMessageTransmisson = d;
        nextIdOfMessage = id;
        id++;
    }


    public byte[] getBytes() throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(bos);
        out.writeInt(nextIdOfMessage);
        out.writeObject(dateOfMessageTransmisson);
        out.writeObject(textDataOfMessage);
        out.close();
        byte[] convertInBytes = bos.toByteArray();
        bos.close();
        return convertInBytes;
    }

    public static Message getMessageFromBytes(byte[] bytes)  throws IOException, ClassNotFoundException {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(bis);
        int msgID = ois.readInt();
        String date = (String)ois.readObject();
        String text = (String)ois.readObject();
        ois.close();
        bis.close();
        Message msgFromBytes = new Message(text, date, msgID);
        return msgFromBytes;
    }

    public String toString() {
        return "[Packet ID = " + nextIdOfMessage + ", date of trans = "
                + dateOfMessageTransmisson + ", text = " + textDataOfMessage + "]";
    }
    
    public boolean equals(Object otherObject) {
        if (this == otherObject) {
            return true;
        }

        if (otherObject == null) {
            return false;
        }

        if (getClass() != otherObject.getClass()) {
            return false;
        }

        Message other = (Message) otherObject;

        return this.toString().equals(other.toString());
    }
    
    private static int id = 0;
    private int nextIdOfMessage;
    private String textDataOfMessage;
    private String dateOfMessageTransmisson;
    private byte data[];
    public static final int MAX_MESSAGE_SIZE = 50;
}
